<script setup>
import { ref } from 'vue'
import { addProjectTypeService, updateProjectTypeService } from '@/api/project.js'

// 控制对话框的显示与隐藏
const visibleDialog = ref(false)

const defaultDTO = {
  projectTypeName: null
}

const projectTypeDTO = ref({ ...defaultDTO })

// 向外暴露方法
const open = (row) => {
  visibleDialog.value = true // 打开对话框
  if (row.id) {
    projectTypeDTO.value = {
      id: row.id,
      projectTypeName: row.name
    }
  } else {
    projectTypeDTO.value = { ...defaultDTO }
  }
}

// 提交逻辑
const emit = defineEmits(['success'])
const handleSubmit = async () => {
  if (projectTypeDTO.value.id) {
    await updateProjectTypeService(projectTypeDTO.value)
    ElNotification({
      title: '修改成功',
      type: 'success'
    })
    visibleDialog.value = false
  } else {
    await addProjectTypeService(projectTypeDTO.value.projectTypeName)
    ElNotification({
      title: '新增成功',
      type: 'success'
    })
    visibleDialog.value = false
  }
  emit('success')
}

// 取消逻辑
const handleCancel = () => {
  visibleDialog.value = false
  projectTypeDTO.value = { ...defaultDTO }
}

defineExpose({
  open
})
</script>

<template>
  <!-- 对话框 -->
  <el-dialog
    v-model="visibleDialog"
    :title="projectTypeDTO.id ? '修改服务项目类型' : '新增服务项目类型'"
    width="500"
  >
    <el-form :model="projectTypeDTO" ref="formRef" label-width="auto">
      <el-form-item label="服务项目类型名称" prop="projectTypeName">
        <el-input
          v-model="projectTypeDTO.projectTypeName"
          placeholder="请输入服务项目类型名称"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button plain @click="handleCancel">取消</el-button>
        <el-button type="primary" plain @click="handleSubmit">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>
